using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using Newtonsoft.Json;

public class SpriteSheetTool
{
    [MenuItem("Custom/SpriteTool/DeleteNotExistSpriteSheet")]
    public static void DeleteNotExistSpriteSheet()
    {
        string rootPath = CreateSpriteSheet.bundleDir[0];
        Platform[] platforms = new Platform[]{ Platform.android, Platform.ios };
        for (int j = 0; j < platforms.Length; j++)
        {
            SpriteSheetConfig rawConfig = EditorCommonTool.getRawSpriteSheetConfig(rootPath);
            SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(rootPath, platforms[j]);
			if(config == null)
			{
				continue;
			}
			
            Dictionary<string, string> parentMap = new Dictionary<string, string>();
            SpriteSheetConfig.Enumerator enumerator = config.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Current.Value.sub_pack_names != null)
                {
                    for (int i = 0; i < enumerator.Current.Value.sub_pack_names.Length; i++)
                    {
                        parentMap.Add(enumerator.Current.Value.sub_pack_names[i], enumerator.Current.Key);
                    }
                }
            }

            HashSet<string> parentSet = new HashSet<string>();
            enumerator = config.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (!parentMap.ContainsKey(enumerator.Current.Key))
                {
                    parentSet.Add(enumerator.Current.Key);
                }
            }

            string sheetDir = rootPath + "/" + EditorCommonTool.getSheetDirName(platforms[j]);
            foreach (string spKey in parentSet)
            {
                if (!rawConfig.ContainsKey(spKey))
                {
                    Dictionary<string, SpriteSheetInfo> deleteGroup = new Dictionary<string, SpriteSheetInfo>();
                    config.getSpriteSheetGroup(spKey, ref deleteGroup);
                    config.DeleteSpriteSheet(spKey);

                    foreach(var entry in deleteGroup)
                    {
                        string spPath = sheetDir + "/" + entry.Key;
                        CommonUtil.Delete(spPath);
                    }
                }
            }

            EditorCommonTool.setBinarySpriteSheetConfig(config, rootPath, platforms[j]);
            EditorCommonTool.setSpriteSheetConfig(config, rootPath, platforms[j]);

			if(System.IO.Directory.Exists(sheetDir))
			{
				string[] dirPaths = System.IO.Directory.GetDirectories(sheetDir, "*", SearchOption.TopDirectoryOnly);
				for (int i = 0; i < dirPaths.Length; i++)
				{
					string dirName = System.IO.Path.GetFileName(dirPaths[i]);
					if (!config.ContainsKey(dirName))
					{
						CommonUtil.Delete(dirPaths[i]);
					}
				}
			}
        }

        AssetDatabase.Refresh();
    }
    
    public static void BuildByDiffFile ()
    {
        CommonUtil.Delete(EditorCommonTool.need_rebuild_spritesheet_filepath);

        string[] args = System.Environment.GetCommandLineArgs();
        string filePath = null;
        string oldConfigPath = null;
        bool all = false;
        HashSet<string> modifiedSpriteSheetNames = new HashSet<string>();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == "-all")
            {
                all = bool.Parse(args[i + 1]);
                if (all)
                {
                    break;
                }
            }

            if (args[i] == "-diffFile")
            {
                filePath = args[i + 1];
            }

            if (args[i] == "-oldConfig")
            {
                oldConfigPath = args[i + 1];
            }

            if (args[i] == "-rebuild")
            {
                string str = args[i + 1];
                if (!string.IsNullOrEmpty(str))
                {
                    string[] modifieds = str.Split(new char[]{ ',' });
                    for (int j = 0; j < modifieds.Length; j++)
                    {
                        modifiedSpriteSheetNames.Add(modifieds[j]);
                    }
                }
            }
        }

        string rootPath = CreateSpriteSheet.bundleDir[0];
        UIFrameSpriteSheet.RebuildSpriteSheetForUIFrame();

        DeleteNotExistSpriteSheet();

        if (all)
        {
            create(rootPath, null, false);
        }
        else
        {
            

            string oldConfigStr = CommonUtil.fileToString(oldConfigPath);
//            Debug.LogError("sp_name: read config: " + oldConfigPath);
            if (!string.IsNullOrEmpty(oldConfigStr))
            {
//                Debug.LogError("sp_name: compare to old conpare");
                SpriteSheetConfig oldConfig = JsonConvert.DeserializeObject<SpriteSheetConfig>(oldConfigStr);
                SpriteSheetConfig curConfig = EditorCommonTool.getRawSpriteSheetConfig(rootPath);
                HashSet<string> changedSpriteSheetNames = EditorCommonTool.getChangedSpriteSheetList(curConfig, oldConfig);

                foreach (string s in changedSpriteSheetNames)
                {
                    modifiedSpriteSheetNames.Add(s);
                }
            }

			HashSet<string> modifiedFiles = EditorCommonTool.ParseDiffFile(filePath);



            SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(rootPath);
            if (config == null)
            {
                return;
            }
            
            List<string> modifiedFileList = new List<string>(modifiedFiles);
			for(int i = 0; i < modifiedFileList.Count; i++)
			{
				modifiedFileList[i] = modifiedFileList[i].Trim();
			}

            getNeedUpdateSpriteSheetName(config, rootPath, modifiedFileList.ToArray(), ref modifiedSpriteSheetNames);

//        Debug.LogError("  " + modifiedFiles.Count + "  " + modifiedFileList.Count);
//        foreach(string spName in modifiedSpriteSheetNames)
//        {
//            Debug.LogError("spName_: " + spName);
//        }

            create(rootPath, modifiedSpriteSheetNames, false);
        }
    }

	[MenuItem("Custom/SpriteSheetTool/BuildSpriteAtlas")]
	public static void BuildSpriteAtlas ()
    {
        UIFrameSpriteSheet.RebuildSpriteSheetForUIFrame();

		string rootPath = CreateSpriteSheet.bundleDir[0];
		string spriteAtlasDir = rootPath + "/" + ResourcesEx.SpriteAtlasDir;

		CommonUtil.CreateDir(spriteAtlasDir);
		
		SpriteSheetConfig config = ConfigTool.CreateRawSpriteSheetConfig(rootPath);

		string[] existSpriteAtlasPaths = CommonUtil.GetFiles(spriteAtlasDir, "*.spriteatlas", SearchOption.AllDirectories);
		HashSet<string> existSpriteAtlasPathSet = new HashSet<string>(existSpriteAtlasPaths);

		foreach(var entry in config)
		{
			SpriteSheetInfo spInfo = entry.Value;
			if(!spInfo.isLeaf())
			{
				continue;
			}

			string altasName = entry.Key;
			string altasPath = spriteAtlasDir + "/" + altasName + ".spriteatlas";

			existSpriteAtlasPathSet.Remove(altasPath);

			UnityEngine.U2D.SpriteAtlas altas = AssetDatabase.LoadAssetAtPath<UnityEngine.U2D.SpriteAtlas>(altasPath);

			bool needCreate = altas == null;
			if(needCreate)
			{
				altas = new UnityEngine.U2D.SpriteAtlas();
				UnityEditor.U2D.SpriteAtlasExtensions.SetIncludeInBuild(altas, false);
				UnityEditor.U2D.SpriteAtlasPackingSettings packingSetting = UnityEditor.U2D.SpriteAtlasExtensions.GetPackingSettings(altas);
				packingSetting.enableTightPacking = false;
				UnityEditor.U2D.SpriteAtlasExtensions.SetPackingSettings(altas, packingSetting);
			}

			UnityEditor.U2D.SpriteAtlasExtensions.Remove(altas, UnityEditor.U2D.SpriteAtlasExtensions.GetPackables(altas));

			
			
			

			
			HashSet<Object> objs = new HashSet<Object>();
			for(int i = 0; i < spInfo.dirs.Length; i++)
			{
				string path = spInfo.dirs[i];
				path = rootPath + "/" + path;

				if(System.IO.Directory.Exists(path))
				{
					Object dirObj = AssetDatabase.LoadAssetAtPath<Object>(path);
					objs.Add(dirObj);
				}
				else
				{
					string[] texExts = ResourceManager.texExts;
					for(int k = 0; k < texExts.Length; k++)
					{
						string texPath = path + texExts[k];
						var texObj = AssetDatabase.LoadAssetAtPath<Object>(texPath);
						if(texObj != null)
						{
							objs.Add(texObj);
						}
					}
				}
			}

			UnityEditor.U2D.SpriteAtlasExtensions.Add(altas, objs.ToArray());

			if(needCreate)
			{
				AssetDatabase.CreateAsset(altas, altasPath);
			}
		}

		foreach(var deletePath in existSpriteAtlasPathSet)
		{
			
			CommonUtil.Delete(deletePath);
		}
		
		AssetDatabase.SaveAssets();
		AssetDatabase.Refresh();
    }


    static bool building = false;
    static bool forceAndoidRgbaSplitAlpha = false;
	static HashSet<string> changeSplitAlphaType (string resPath, BuildTarget target, HashSet<string> hashSet, Dictionary<string, string> map = null, bool revert = false)
	{
		HashSet<string> changeSet = new HashSet<string> ();
		SpriteSheetConfig rawConfig = ConfigTool.CreateRawSpriteSheetConfig(resPath);
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig (resPath, EditorCommonTool.getPlatform(target));
		foreach (string set in hashSet)
		{
			SpriteSheetInfo info = null;
			config.TryGetValue (set, out info);
			SpriteSheetInfo rawInfo = null;
			if(map != null)
			{
				string parentName = null;
				if(map.TryGetValue(set, out parentName))
				{
					rawConfig.TryGetValue (parentName, out rawInfo);
				}
			}

			if(rawInfo == null)
			{
				rawConfig.TryGetValue (set, out rawInfo);
			}

			if(target == BuildTarget.Android)
			{
                if (forceAndoidRgbaSplitAlpha)
                {
                    if (info.isPng(resPath))
                    {
                        info.split_alpha_type = SplitAlphaType.SPLIT_TEX;
                    }
                    else
                    {
                        info.split_alpha_type = SplitAlphaType.NONE;
                    }
                }
			}
			else
			{
				if(info == null || rawInfo == null)
				{
					Debug.LogError("info is null:" + set + " " + (info == null) + " " + (rawInfo == null));
				}

				if(revert)
				{
					info.split_alpha_type = rawInfo.split_alpha_type;
				}
				else
				{
					if (info.is_from_interface && false)
					{
						if (info.split_alpha_type == SplitAlphaType.NONE)
						{
							bool isPng = info.isPng (resPath);
							if (isPng)
							{
								info.split_alpha_type = SplitAlphaType.SPLIT_TEX;
								changeSet.Add (set);
							}
						}
					}
				}
			}
		}

		EditorCommonTool.setSpriteSheetConfig(config, resPath, EditorCommonTool.getPlatform(target));
		return changeSet;
	}

    [MenuItem("Custom/SpriteTool/CreateAllSpriteSheet")]
    public static void createAllSpriteSheet()
    {
        building = true;
        create(CreateSpriteSheet.bundleDir[0], null, false);
        building = false;
    }

//	[MenuItem("Custom/SpriteTool/CreateNeedSpriteSheet")]
//	static void createSpriteSheet()
//	{
//        building = true;
//		create(CreateSpriteSheet.bundleDir[0], EditorCommonTool.need_rebuild_spritesheet_filepath, false);
//
////		ConfigTool.createPlatfromBundleConfig();
//        building = false;
//	}

	static void convertToRevertSet (string resPath, HashSet<string> changeSet)
	{
		HashSet<string> tempSet = new HashSet<string> (changeSet);
		foreach (string set in tempSet)
		{
            bool found = false;
            for (int i = 0; i < MaterialTextureForETC1.exts.Length; i++)
            {
                string texPath = resPath + "/" + EditorCommonTool.getSheetDirName (EditorCommonTool.getPlatform (EditorCommonTool.build_target_ios)) + "/" + set + "/" + set + ResourcesEx.SpriteSheetTexSuffix + MaterialTextureForETC1.exts[i];
    			Texture2D tex = AssetDatabase.LoadAssetAtPath (texPath, typeof(Texture2D)) as Texture2D;
    			if(tex == null)
    			{
                    continue;
    			}

    			if (tex.width != tex.height)
    			{
    				changeSet.Remove (set);
    			}
    			Resources.UnloadAsset (tex);
                found = true;
                break;
            }

            if (!found)
            {
                Debug.LogError("not found spritesheet: " + set);
            }
		}
	}

	static void backupSpriteSheetConfig(string resPath, BuildTarget target, bool isBackup, HashSet<string> spriteSheets = null)
	{
		if(isBackup)
		{
			if(File.Exists(EditorCommonTool.getSpriteSheetConfigPath(resPath, EditorCommonTool.getPlatform(target), "_2")))
			{
				return;
			}
			SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, EditorCommonTool.getPlatform(target));
			EditorCommonTool.setSpriteSheetConfig(config, resPath, EditorCommonTool.getPlatform(target), "_2");
		}
		else
		{
			SpriteSheetConfig oldConfig = EditorCommonTool.getSpriteSheetConfig(resPath, EditorCommonTool.getPlatform(target), "_2");
			if(oldConfig != null)
			{
				SpriteSheetConfig newConfig = EditorCommonTool.getSpriteSheetConfig(resPath, EditorCommonTool.getPlatform(target));
				foreach(string groupName in spriteSheets)
				{
					Dictionary<string, SpriteSheetInfo> newSpriteSheets = new Dictionary<string, SpriteSheetInfo>();
					newConfig.getSpriteSheetGroup(groupName, ref newSpriteSheets);
					Dictionary<string, SpriteSheetInfo> oldSpriteSheets = new Dictionary<string, SpriteSheetInfo>();
					oldConfig.getSpriteSheetGroup(groupName, ref oldSpriteSheets);

					HashSet<string> removeSpriteSheet = new HashSet<string>();
					Dictionary<string, SpriteSheetInfo>.Enumerator e = oldSpriteSheets.GetEnumerator();
					{
						while(e.MoveNext())
						{
							oldConfig.Remove(e.Current.Key);
							removeSpriteSheet.Add(e.Current.Key);
						}
					}

					Dictionary<string, SpriteSheetInfo>.Enumerator e2 = newSpriteSheets.GetEnumerator();
					{
						while(e2.MoveNext())
						{
							oldConfig.Add(e2.Current.Key, e2.Current.Value);
							removeSpriteSheet.Remove(e2.Current.Key);
						}
					}

					foreach(string removeSp in removeSpriteSheet)
					{
						string path = resPath + "/" + EditorCommonTool.getSheetDirName(target.getPlatform()) + "/" + removeSp;
						CommonUtil.Delete(path);
					}
				}
			}
			EditorCommonTool.setSpriteSheetConfig(oldConfig, resPath, EditorCommonTool.getPlatform(target));
			CommonUtil.Delete(EditorCommonTool.getSpriteSheetConfigPath(resPath, EditorCommonTool.getPlatform(target), "_2"));
		}
	}

    static void create(string resPath, HashSet<string> modifiedSet, bool local)
	{
		MaterialTextureForETC1.DeleteOldSpriteSheet();

//		SpriteSheetConfig config = EditorCommonTool.getRawSpriteSheetConfig(resPath);
//		HashSet<string> hashSet = new HashSet<string>(config.Keys);
//		HashSet<string> groupHashSet = new HashSet<string>(config.Keys);

//        if(!string.IsNullOrEmpty(rawSheetPath) && !File.Exists(rawSheetPath))
//		{
//			return;
//		}

        SpriteSheetConfig spriteSheetConfig = ConfigTool.CreateRawSpriteSheetConfig(resPath);

        HashSet<string> groupHashSet = null;

        if (modifiedSet == null)
        {
            modifiedSet = new HashSet<string>();
            groupHashSet = new HashSet<string>();
            Dictionary<string, SpriteSheetInfo>.Enumerator en = spriteSheetConfig.GetEnumerator();
            while(en.MoveNext())
            {
                if (en.Current.Value.sub_pack_names != null && en.Current.Value.sub_pack_names.Length > 0)
                {
                    modifiedSet.Add(en.Current.Key);
                    groupHashSet.Add(en.Current.Key);
                }
            }
        }
        else
        {
            groupHashSet = new HashSet<string>(modifiedSet);
//            string str = CommonUtil.fileToString(rawSheetPath);
//            modifiedSet = JsonConvert.DeserializeObject<HashSet<string>>(str);
//            groupHashSet = JsonConvert.DeserializeObject<HashSet<string>>(str);
        }

		HashSet<string> temp = new HashSet<string>();
		foreach(string spriteSheetName in modifiedSet)
		{
			SpriteSheetInfo info = null;
			spriteSheetConfig.TryGetValue(spriteSheetName, out info);
			if(info == null)
			{
				Debug.LogError("not found sprite sheet config:" + spriteSheetName);
				continue;
			}

            if (info.sub_pack_names == null)
            {
                Debug.LogError("sub_pack_names is null:" + spriteSheetName);
                continue;
            }

			for(int i = 0; i < info.sub_pack_names.Length; i++)
			{
				temp.Add(info.sub_pack_names[i]);
			}
		}
		modifiedSet = temp;

		bool hasError = false;
		foreach(string sheetName in modifiedSet)
		{
			SpriteSheetInfo spriteSheetInfo = null;
			if(!spriteSheetConfig.TryGetValue(sheetName, out spriteSheetInfo))
			{
				Debug.LogError("don't has sprite sheet: " + sheetName);
				hasError = true;
				continue;
			}
			
			foreach(string dir in spriteSheetInfo.dirs)
			{
				string realDir = resPath + "/" + dir;
				if(!Directory.Exists(realDir))
				{
					string srcPath = realDir + ".png";
					if(!File.Exists(srcPath))
					{
						srcPath = realDir + ".jpg";
						if(!File.Exists(srcPath))
						{
							Debug.LogError("sprite sheet dir don't exist: " + realDir);
							hasError = true;
						}
					}
				}
			}
		}
		
		if(hasError)
		{
			return;
		}

//		BuildTarget[] platforms = new BuildTarget[]{EditorCommonTool.build_target_ios};
//		BuildTarget[] platforms = new BuildTarget[]{BuildTarget.Android};
		BuildTarget[] platforms = new BuildTarget[]{BuildTarget.Android, EditorCommonTool.build_target_ios};
		for(int i = 0; i < platforms.Length; i++)
		{
			BuildTarget platform = platforms[i];

			HashSet<string> tempSet = new HashSet<string>(modifiedSet);
            Debug.Log("build_sprite_sheet: 0: " + platform + "  " + modifiedSet.Count);
			backupSpriteSheetConfig(resPath, platform, true);

			Debug.Log("build_sprite_sheet: 0.5: " + platform);
			SpriteSheetConfig spriteSheetConfig2 = ConfigTool.CreateRawSpriteSheetConfig(resPath);
			if(platform == EditorCommonTool.build_target_ios)
			{
				Dictionary<string, SpriteSheetInfo>.Enumerator en = spriteSheetConfig2.GetEnumerator();
				while(en.MoveNext())
				{
					en.Current.Value.scale = 0;
				}
			}
			EditorCommonTool.setSpriteSheetConfig(spriteSheetConfig2, resPath, platform.getPlatform());

            Debug.Log("build_sprite_sheet: 0.5.0.1: " + platform);
			HashSet<string> changeSet = changeSplitAlphaType (resPath, platform, tempSet);
            Debug.Log("build_sprite_sheet: 0.5.0.2: " + platform);
			Dictionary<string, Dictionary<string, HashSet<string>>> subPackMap = CreateSpriteSheet.createAllSpriteSheet5(resPath, platform, tempSet);

			Dictionary<string, string> changeSetMap = new Dictionary<string, string>();

            Debug.Log("build_sprite_sheet: 0.5.1: " + platform + "   " + subPackMap.Count);

			if(subPackMap.Count > 0)
			{
				SpriteSheetConfig tempConfig = EditorCommonTool.getSpriteSheetConfig(resPath, platform.getPlatform());
				Dictionary<string, Dictionary<string, HashSet<string>>>.Enumerator e3 = subPackMap.GetEnumerator();
				while(e3.MoveNext())
				{
					string parentName = e3.Current.Key;

                    Debug.Log("build_sprite_sheet: 0.5.2: " + parentName);

					if(e3.Current.Value.Count > 0)
					{
						tempSet.Remove(parentName);
						bool removed = changeSet.Remove(parentName);

						SpriteSheetInfo parentInfo = null;
						tempConfig.TryGetValue(parentName, out parentInfo);
						Dictionary<string, HashSet<string>>.Enumerator e4 = e3.Current.Value.GetEnumerator();
						while(e4.MoveNext())
						{
							tempSet.Add(e4.Current.Key);
							if(removed)
							{
								changeSet.Add(e4.Current.Key);
								changeSetMap.Add(e4.Current.Key, parentName);
							}

							SpriteSheetInfo newInfo = new SpriteSheetInfo();
							newInfo.is_sub_pack = true;
							newInfo.heuristic_mask = parentInfo.heuristic_mask;
							newInfo.edge_extrude = parentInfo.edge_extrude;
							newInfo.is_from_interface = parentInfo.is_from_interface;
							newInfo.alpha_threshold = parentInfo.alpha_threshold;
							newInfo.split_alpha_type = parentInfo.split_alpha_type;
							newInfo.multi_pack = parentInfo.multi_pack;
							newInfo.max_size = parentInfo.max_size;
							List<string> subPackPaths = new List<string>(e4.Current.Value);
							newInfo.dirs = subPackPaths.ToArray();
							tempConfig.Add(e4.Current.Key, newInfo);
						}

						List<string> subPackNames = new List<string>(e3.Current.Value.Keys);
						parentInfo.sub_pack_names = subPackNames.ToArray();
					}

                    Debug.Log("build_sprite_sheet: 0.5.3: " + parentName);
				}
				
				EditorCommonTool.setSpriteSheetConfig(tempConfig, resPath, platform.getPlatform());
			}




			Debug.Log("build_sprite_sheet: 1: " + platform);
			MaterialTextureForETC1.ChangeSpriteSheetSpriteTypeToMulti2(resPath, platform, tempSet);

            Debug.Log("build_sprite_sheet: 2: " + platform);
            if(platform == EditorCommonTool.build_target_ios)
            {
                convertToRevertSet (resPath, changeSet);
                changeSplitAlphaType (resPath, platform, changeSet, changeSetMap, true);
            }

			Debug.Log("build_sprite_sheet: 3: " + platform);
			MaterialTextureForETC1.SeperateAllTexturesRgbAndAlpha2(resPath, platform, tempSet);
			Debug.Log("build_sprite_sheet: 4: " + platform);
			MaterialTextureForETC1.CreateSpriteSheetMaterial3(resPath, platform, tempSet);



			Debug.Log("build_sprite_sheet: 5: " + platform);
			if(platform == EditorCommonTool.build_target_ios)
			{
				MaterialTextureForETC1.MergeAlpha(resPath, platform, tempSet);
			}

			Debug.Log("build_sprite_sheet: 6: " + platform);
			DeleteNotNeedFiles(resPath, platform, tempSet);
			Debug.Log("build_sprite_sheet: 7: " + platform);
			backupSpriteSheetConfig(resPath, platform, false, groupHashSet);

			SpriteSheetConfig newConfig = EditorCommonTool.getSpriteSheetConfig(resPath, platform.getPlatform());
			EditorCommonTool.setBinarySpriteSheetConfig(newConfig, resPath, platform.getPlatform());

			MaterialTextureForETC1.CreateSpriteSheetConfig3(resPath, platform, tempSet);

            AssetDatabase.Refresh();

            MaterialTextureForETC1.CreateSpriteSheetLoaderScript(resPath, platform, tempSet);
            MaterialTextureForETC1.CreateSpriteToSheetMap(resPath, platform, tempSet);
		}

		Debug.Log("build_sprite_sheet: 9: ");

//		if(File.Exists(rawSheetPath))
//		{
//			CommonUtil.Move(rawSheetPath, CommonUtil.addSuffixToFileName(rawSheetPath, "_backup"));
//		}

//		if(File.Exists(EditorCommonTool.interfaceFile))
//		{
//			CommonUtil.Move(EditorCommonTool.interfaceFile, CommonUtil.addSuffixToFileName(EditorCommonTool.interfaceFile, "_backup"));
//		}

		AssetDatabase.Refresh();

//		MaterialTextureForETC1.CreateSpriteSheetConfig2(resPath, EditorCommonTool.build_target_ios, hashSet, () =>
//		{
//			Debug.Log("build_sprite_sheet: 10: ");
//			MaterialTextureForETC1.CreateSpriteSheetConfig2(resPath, BuildTarget.Android, hashSet, () =>
//			{
//				Debug.Log("build_sprite_sheet: 11: ");
//				Debug.Log("CreateSpriteSheetConfig2 finish");
//				if(File.Exists(rawSheetPath))
//				{
//					File.Move(rawSheetPath, addSuffixToFileName(rawSheetPath));
//				}
//
//				if(File.Exists(interfaceFile))
//				{
//					File.Move(interfaceFile, addSuffixToFileName(interfaceFile));
//				}
//				AssetDatabase.Refresh();
//			});
//		});
	}

	public static void DeleteNotNeedFiles(string resPath, BuildTarget target, HashSet<string> hashSet)
	{
		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath, EditorCommonTool.getPlatform(target));
		foreach(string name in config.Keys)
		{
			if(!hashSet.Contains(name))
			{
				continue;
			}

			SpriteSheetInfo info = null;
			config.TryGetValue(name, out info);
			if(info.split_alpha_type == SplitAlphaType.NONE)
			{
				CommonUtil.Delete(resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + name + "/" + name + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.SpriteSheetAlphaSuffix + ".png");
				CommonUtil.Delete(resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + name + "/" + name + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetMaterialSuffix + ".mat");
				CommonUtil.Delete(resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + name + "/" + name + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.spriteSheetUiMaterialSuffix + ".mat");
			}
			else if(info.split_alpha_type != SplitAlphaType.SPLIT_TEX)
			{
				CommonUtil.Delete(resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + name + "/" + name + ResourcesEx.SpriteSheetTexSuffix + ResourcesEx.SpriteSheetAlphaSuffix + ".png");
			}

			string pngSrcPath = resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + name + "/" + name + ResourcesEx.SpriteSheetTexSuffix + ".png";
			string jpgSrcPath = resPath + "/" + EditorCommonTool.getSheetDirName(EditorCommonTool.getPlatform(target)) + "/" + name + "/" + name + ResourcesEx.SpriteSheetTexSuffix + ".jpg";
			if(File.Exists(jpgSrcPath) && File.Exists(pngSrcPath))
			{
				if(info.split_alpha_type != SplitAlphaType.NONE)
				{
					CommonUtil.Delete(jpgSrcPath);
				}
				else
				{
					System.DateTime pngTime = File.GetCreationTime(pngSrcPath);
					System.DateTime jpgTime = File.GetCreationTime(jpgSrcPath);
					if(pngTime > jpgTime)
					{
						CommonUtil.Delete(jpgSrcPath);
					}
					else
					{
						CommonUtil.Delete(pngSrcPath);
					}
				}
			}
		}
	}

//	static void OnPostprocessAllAssets (
//		string[] importedAssets,
//		string[] deletedAssets,
//		string[] movedAssets,
//		string[] movedFromAssetPaths)
//	{
//		if(SwitchConfig.isBambooBuild)
//		{
//			return;
//		}
//
//        if (building)
//        {
//            return;
//        }
//
////		if(!File.Exists("/usr/local/bin/TexturePacker"))
////		{
////			return;
////		}
//
//		test(CreateSpriteSheet.bundleDir[0], EditorCommonTool.need_rebuild_spritesheet_filepath, importedAssets, deletedAssets, movedAssets, movedFromAssetPaths);
//	}

	static void test(string resPath, string rawFilePath, string[] importedAssets,
	                 string[] deletedAssets,
	                 string[] movedAssets,
	                 string[] movedFromAssetPaths)
	{
		HashSet<string> spriteSheetNames = new HashSet<string>();

		SpriteSheetConfig config = EditorCommonTool.getSpriteSheetConfig(resPath);
		if(config == null)
		{
			return;
		}
		getNeedUpdateSpriteSheetName(config, resPath, importedAssets, ref spriteSheetNames);
		getNeedUpdateSpriteSheetName(config, resPath, deletedAssets, ref spriteSheetNames);
		getNeedUpdateSpriteSheetName(config, resPath, movedAssets, ref spriteSheetNames);
		getNeedUpdateSpriteSheetName(config, resPath, movedFromAssetPaths, ref spriteSheetNames);
		
		modifySpritesheet (rawFilePath, spriteSheetNames);
	}
	
	static void getNeedUpdateSpriteSheetName(SpriteSheetConfig config, string resPath, string[] paths, ref HashSet<string> spriteSheetNames)
	{
		if(paths == null)
		{
			return;
		}

		string spritePath = resPath + "/";

		ResourcesEx.Reset();

		HashSet<string> rawInterfaceSet = new HashSet<string>();

		for(int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			if(!path.Contains(spritePath))
			{
				continue;
			}

			if(path.Contains(ResourcesEx.SheetDirName))
			{
				continue;
			}
			
			string spritePath2 = path.Replace(spritePath, "");
			string spriteSheetName = null;
			string spriteName = null;
            spriteSheetName = config.getSpriteSheetName(spritePath2, true);

            if(spriteSheetName != null)
			{
				SpriteSheetInfo info = null;
				if(config.TryGetValue(spriteSheetName, out info))
				{
					spriteSheetNames.Add(spriteSheetName);
				}
			}

//			if(spritePath2.Contains(MakeWindow.dir))
//			{
//				string ext = Path.GetExtension(spritePath2);
//				string realPath = spritePath2;
//				if(!string.IsNullOrEmpty(ext))
//				{
//					realPath = spritePath2.Replace(ext, "");
//				}
//
//				rawInterfaceSet.Add(realPath);
//			}
		}

		if(rawInterfaceSet.Count > 0)
		{
            AddChangeInterface(rawInterfaceSet);
		}
	}

    public static void AddChangeInterface(HashSet<string> changedSet)
    {
        string str = CommonUtil.fileToString(EditorCommonTool.interfaceFile);
        HashSet<string> interfaceFileSet = null;
        if (str != null)
        {
            interfaceFileSet = JsonConvert.DeserializeObject<HashSet<string>>(str);
            foreach (string interfacefile in changedSet)
            {
                interfaceFileSet.Add(interfacefile);
            }
        }
        else
        {
            interfaceFileSet = changedSet;
        }
        string newStr = JsonConvert.SerializeObject(interfaceFileSet, Formatting.Indented);
        CommonUtil.stringToFile(EditorCommonTool.interfaceFile, newStr);
    }

    public static void modifySpritesheet (string rawFilePath, HashSet<string> spriteSheetNames)
    {
        if (spriteSheetNames.Count > 0) {
            HashSet<string> hashSet = null;
            if (File.Exists (rawFilePath)) {
                string str = CommonUtil.fileToString (rawFilePath);
                hashSet = JsonConvert.DeserializeObject<HashSet<string>> (str);
                if (hashSet != null) {
                    foreach (string sheet in hashSet) {
                        spriteSheetNames.Add (sheet);
                    }
                }
            }
            string content = JsonConvert.SerializeObject (spriteSheetNames, Newtonsoft.Json.Formatting.Indented);
            CommonUtil.stringToFile (rawFilePath, content);
            AssetDatabase.Refresh ();
        }
    }

	static void resetFootPrintMaterial(Material material, Sprite sprite)
	{
		material.mainTexture = sprite.texture;
		Vector2 size = new Vector2(sprite.rect.width / sprite.texture.width, sprite.rect.height / sprite.texture.height);
		material.SetTextureScale("_MainTex", size);
		Vector2 offset = new Vector2(sprite.rect.x / sprite.texture.width, sprite.rect.y / sprite.texture.height);
		material.SetTextureOffset("_MainTex", offset);
	}

	[MenuItem("Custom/SpriteSheetTool/DeleteSpriteSheetConfig")]
	static void DeleteSpriteSheetConfig()
	{
		Platform[] ps = new Platform[]{Platform.android, Platform.ios};
		for(int i = 0; i < ps.Length; i++)
		{
			string dir = ResourcesEx.BundleResDir + "/" + ps[i];
			string[] files = System.IO.Directory.GetFiles(dir, "*sprite_sheet*", SearchOption.AllDirectories);
			for(int j = 0; j < files.Length; j++)
			{
				Trash.Delete(files[j]);
			}
		}

		AssetDatabase.Refresh();
	}

	[MenuItem("Custom/SpriteSheetTool/DeleteSpriteSheet")]
	static void DeleteSpriteSheet()
	{
		Platform[] ps = new Platform[]{Platform.android, Platform.ios};
		for(int i = 0; i < ps.Length; i++)
		{
			string dir = ResourcesEx.BundleResDir + "/" + ps[i];
			Trash.Delete(dir + "/sprite_sheet");

			string[] files = System.IO.Directory.GetFiles(dir, "*sprite_sheet*", SearchOption.AllDirectories);
			for(int j = 0; j < files.Length; j++)
			{
				Trash.Delete(files[j]);
			}
		}

		AssetDatabase.Refresh();

		CommonUtil.Delete(ResourcesEx.BundleResDir + "/" + ResourcesEx.SpriteAtlasDir);
	}

	[MenuItem("Custom/SpriteSheetTool/EnableSpriteAtlasForBuild")]
	static void EnableSpriteAtlasForBuild()
	{
		EditorSettings.spritePackerMode = SpritePackerMode.BuildTimeOnlyAtlas;
	}

	[MenuItem("Custom/SpriteSheetTool/DisableSpriteAtlas")]
	static void DisableSpriteAtlas()
	{
		EditorSettings.spritePackerMode = SpritePackerMode.Disabled;
	}
}
